package com.sdp.right.control;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.redis.RedisUtil;
import com.sdp.core.bizc.utils.SnowFlake;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.cache.keys.RightCacheKeys;
import com.sdp.right.db.sys_dr.service.ISysDrService;
import com.sdp.right.db.sys_dr_emp_rule.service.ISysDrEmpRuleService;
import com.sdp.right.db.sys_dr_role_rule.service.ISysDrRoleRuleService;
import com.sdp.right.entity.SysDr;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/SysDrController")
public class SysDrController {
	
	@Autowired
	private ISysDrService iSysDrService;
	
	@Autowired
	private ISysDrRoleRuleService iSysDrRuleService;
	
	@Autowired
	private ISysDrEmpRuleService iSysDrEmpRuleService;
	
	@Autowired
	private Query query;
	
	@Autowired
	private SnowFlake snowFlake;
	
	@Autowired
	private RedisUtil redisUtil;

	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iSysDrService, SysDr.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional
	public Result<?> save(@RequestBody SysDr sysDr){
		if(sysDr==null) {
			return Result.error("数据权限方案信息为空");
		}
		
		if(StringUtils.isEmpty(sysDr.getKeyId())) {
			sysDr.setDrNo(snowFlake.createOrderNo());
			iSysDrService.save(sysDr);
		}else {
			iSysDrService.updateById(sysDr);
		}
	
		return Result.ok(sysDr);
	}
	
	@GetMapping(value = "/del")
	@Transactional
	public Result<?> del(@RequestParam(name="keyId",required=true) String keyId,@RequestParam(name="drNo",required=true) String drNo) {
		if(StringUtils.isEmpty(keyId) || StringUtils.isEmpty(drNo)) {
			return Result.error("需要删除的记录的主键不存在");
		}
		iSysDrService.removeById(keyId);
		Map<String,Object> columnMap = new HashMap<>();
		columnMap.put("dr_no", drNo);
		iSysDrRuleService.removeByMap(columnMap);
		iSysDrEmpRuleService.removeByMap(columnMap);
		
		//删除缓存
		redisUtil.del(RightCacheKeys.DR_ROLE_CACHE_KEY);
		redisUtil.del(RightCacheKeys.DR_EMP_CACHE_KEY);
		return Result.ok();
	}

}

